#include "degfx/font.h"
#include <assert.h>

/**font !The height in pixels of a font
This function return the height of a font in pixels. */
unsigned int mx_font_height(const MX_FONT * font)
{
	/** If the font argument is 0 then the default font be used. */
	if (!font)
		font = MXREF(mx__fontref);
	if (!font)
		font = &MX_FONT_DEFAULT;
	assert(font);

	return font->_height;
}

/**font !The width in pixels of some text
This function return the width of a portion of text in pixels. */
unsigned int mx_font_width(const MX_FONT * font, const char *text, int num)
{
	int count = 0;
	unsigned int len = 0;
	const MX__FONT_INDEX *range = 0;

	/** If the font argument is 0 then the default font be used. */
	if (!font)
		font = MXREF(mx__fontref);
	if (!font)
		font = &MX_FONT_DEFAULT;
	assert(font);
	assert(font->_sections != 0);

	/** If the length of characters is less than 0 then the text is assumed
        to be zero terminated. */
	if (num < 0)
		num = 0x7fff;

	while ((text) && (*text) && (count < num)) {
		const unsigned int clen = mx_utf8_len(text);
		const long c = mx_utf8_char(text, clen);

		/* Find the new range for the mx_font if we need */
		if ((!range) || (c < range->_start)
			|| (c >= (range->_start + 128)))
			range = mx__font_range(font, c);

		if (range)
			len += range->_width[c - range->_start];

		text += clen;
		++count;
	}
	return len;
}
